//
//  CreateJobFirstView.swift
//  GreenDeal
//
//  Created by Moennig Q on 1/3/2023.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxGesture
class CreateJobCompanyAgentView: CreateJobBaseView {
    @objc dynamic var viewModel: CreateJobViewModel!
    var companyListObserver: BehaviorRelay<[CompanyModel]> = BehaviorRelay(value: [])
    var agentListObserver: BehaviorRelay<[AgentModel]> = BehaviorRelay(value: [])
    let companyTableView = UITableView()
    let agentTableView = UITableView()
    let companyRequiredTipLabel = ViewFactory.shared.generateRequiredLabel()
    let agentRequiredTipLabel = ViewFactory.shared.generateRequiredLabel()
    let creditOptionLabel = OptionTypeLabel(R.string.localizable.oswCredit(),topBottomPadding: 12)
    let cashOptionLabel = OptionTypeLabel(R.string.localizable.cash(),topBottomPadding: 12)
    let tradeModeRequiredTipLabel = ViewFactory.shared.generateRequiredLabel()
    let poReferenceTextField = TextFieldWithRequiredView(.text250)
    //
    var companyTableViewHeightConstraint: Constraint?
    var agentTableViewHeightConstraint: Constraint?
    
    override func setUpContentView() {
        //company
        let companyTitle = TitleLabelWithRequired(R.string.localizable.company())
        contentView.addSubview(companyTitle)
        companyTitle.snp.makeConstraints { make in
            make.top.equalTo(Constant.AllOutMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.width.height.greaterThanOrEqualTo(0)
        }
        companyTableView.separatorStyle = .none
        contentView.addSubview(companyTableView)
        companyTableView.snp.makeConstraints { make in
            make.top.equalTo(companyTitle.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyTitle)
            make.right.equalTo(-Constant.AllOutMargin)
            self.companyTableViewHeightConstraint = make.height.equalTo(0).constraint
        }
        //company tip msg
        contentView.addSubview(companyRequiredTipLabel)
        companyRequiredTipLabel.snp.makeConstraints { make in
            make.top.equalTo(companyTableView.snp.bottom)
            make.left.equalTo(companyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //agent
        let agentTitle = TitleLabelWithRequired(R.string.localizable.agent())
        contentView.addSubview(agentTitle)
        agentTitle.snp.makeConstraints { make in
            make.top.equalTo(companyRequiredTipLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(companyTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        agentTableView.separatorStyle = .none
        contentView.addSubview(agentTableView)
        agentTableView.snp.makeConstraints { make in
            make.top.equalTo(agentTitle.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.right.equalTo(companyTableView)
            self.agentTableViewHeightConstraint = make.height.equalTo(0).constraint
        }
        //agent tip msg
        contentView.addSubview(agentRequiredTipLabel)
        agentRequiredTipLabel.snp.makeConstraints { make in
            make.top.equalTo(agentTableView.snp.bottom)
            make.left.equalTo(companyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //trade mode
        let tradeModeTitle = LabelWithRedStarView(R.string.localizable.tradeMode())
        contentView.addSubview(tradeModeTitle)
        tradeModeTitle.snp.makeConstraints { make in
            make.top.equalTo(agentRequiredTipLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(companyTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        //osw creadit
        contentView.addSubview(creditOptionLabel)
        creditOptionLabel.snp.makeConstraints { make in
            make.top.equalTo(tradeModeTitle.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(companyTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        //crash
        contentView.addSubview(cashOptionLabel)
        cashOptionLabel.snp.makeConstraints { make in
            make.top.size.equalTo(creditOptionLabel)
            make.left.equalTo(creditOptionLabel.snp.right).offset(Constant.InternalMargin)
            make.right.equalTo(companyTableView)
        }
        //trade mode tip msg
        contentView.addSubview(tradeModeRequiredTipLabel)
        tradeModeRequiredTipLabel.snp.makeConstraints { make in
            make.top.equalTo(creditOptionLabel.snp.bottom)
            make.left.equalTo(companyTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //trade mode
        let poReferenceTitle = LabelWithRedStarView(R.string.localizable.poReference())
        contentView.addSubview(poReferenceTitle)
        poReferenceTitle.snp.makeConstraints { make in
            make.top.equalTo(tradeModeRequiredTipLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(companyTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        poReferenceTextField.textField.placeholder = "Your reference for this Job"
        contentView.addSubview(poReferenceTextField)
        poReferenceTextField.snp.makeConstraints { make in
            make.top.equalTo(poReferenceTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(companyTitle)
            make.right.equalTo(companyTableView)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-Constant.AllOutMargin)
        }
        
        self.companyTableView.register(RadioBtnTableViewCell.self, forCellReuseIdentifier: RadioBtnTableViewCell.reuseCellIdentifier)
        self.agentTableView.register(RadioBtnTableViewCell.self, forCellReuseIdentifier: RadioBtnTableViewCell.reuseCellIdentifier)
        //
        //设置cell信息
        companyListObserver.bind(to: companyTableView.rx.items(cellIdentifier: RadioBtnTableViewCell.reuseCellIdentifier,cellType: RadioBtnTableViewCell.self)){[weak self] (row, model, cell) in
            guard let strongSelf = self else {return}
            cell.descripLabel.text = model.name
            if strongSelf.viewModel.summaryViewModel.company_id == model.id {
                cell.radioImageView.image  = R.image.createjob_radio_sel()
            }else{
                cell.radioImageView.image  = R.image.createjob_radio_unsel()
            }
        }.disposed(by: self.disposeBag)
        //选择某company
        companyTableView.rx.itemSelected.bind{ [weak self](indexPath) in
            guard let strongSelf = self else {return}
            let data  = strongSelf.companyListObserver.value[indexPath.row]
            if data.id != strongSelf.viewModel.summaryViewModel.company_id{
                strongSelf.viewModel.summaryViewModel.company_id =  data.id
                strongSelf.viewModel.summaryViewModel.company_name =  data.name
                
                strongSelf.companyRequiredTipLabel.text = ""
                strongSelf.companyTableView.reloadData()
                //clear agent info
                strongSelf.viewModel.summaryViewModel.agent_id = 0
                strongSelf.viewModel.summaryViewModel.agent_name = ""
                strongSelf.getAgentList()
            }
        }.disposed(by: disposeBag)
        //设置cell信息
        agentListObserver.bind(to: agentTableView.rx.items(cellIdentifier: RadioBtnTableViewCell.reuseCellIdentifier,cellType: RadioBtnTableViewCell.self)){[weak self] (row, model, cell) in
            guard let strongSelf = self else {return}
            cell.descripLabel.text = model.name
            if strongSelf.viewModel.summaryViewModel.agent_id == model.id {
                cell.radioImageView.image  = R.image.createjob_radio_sel()
            }else{
                cell.radioImageView.image  = R.image.createjob_radio_unsel()
            }
        }.disposed(by: self.disposeBag)
        //选择某一agent
        agentTableView.rx.itemSelected.bind{ [weak self](indexPath) in
            guard let strongSelf = self else {return}
            let data  = strongSelf.agentListObserver.value[indexPath.row]
            if data.id != strongSelf.viewModel.summaryViewModel.agent_id{
                strongSelf.viewModel.summaryViewModel.agent_id = data.id
                strongSelf.viewModel.summaryViewModel.agent_name = data.name
                
                strongSelf.agentRequiredTipLabel.text = ""
                strongSelf.agentTableView.reloadData()
            }
        }.disposed(by: disposeBag)
        //
        companyTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.companyTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        
        agentTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.agentTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //
        //选择osw credit
        creditOptionLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            //重复点击credit，不做处理
            if strongSelf.viewModel.summaryViewModel.trade_mode != .credit {
                strongSelf.changeTradeMode(.credit)
            }
        }).disposed(by: self.disposeBag)
        //选择cash
        cashOptionLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            //重复点击credit，不做处理
            if strongSelf.viewModel.summaryViewModel.trade_mode != .cash {
                strongSelf.changeTradeMode(.cash)
            }
        }).disposed(by: self.disposeBag)
        //po reference
        poReferenceTextField.editingDidEndClosure = {[weak self] (text) in
            guard let strongSelf = self else {return}
            strongSelf.viewModel.summaryViewModel.customer_po = text
        }
    }
    
    //MARK: - 选择TradeMode
    private func changeTradeMode(_ tradeMode: TradeMode){
        self.viewModel.summaryViewModel.trade_mode = tradeMode
        if tradeMode == .credit {//credit
            self.creditOptionLabel.setSelect()
            self.cashOptionLabel.setUnSelect()
            
        }else if tradeMode == .cash {//cash
            self.creditOptionLabel.setUnSelect()
            self.cashOptionLabel.setSelect()
        }
        self.tradeModeRequiredTipLabel.text = ""
    }
    //
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //
        let companyIdValid = self.viewModel.summaryViewModel.rx.observe(Int.self, "company_id").map({($0 ?? 0) > 0}).share(replay: 1)
        let agentIdValid = self.viewModel.summaryViewModel.rx.observe(Int.self, "agent_id").map({($0 ?? 0) > 0}).share(replay: 1)
        let tradeModeValid = self.viewModel.summaryViewModel.rx.observe(String.self, "trade_mode_value").map({($0 ?? "").count > 0}).share(replay: 1)
        let poReferenceValid = self.viewModel.summaryViewModel.rx.observe(String.self, "customer_po").map({($0 ?? "").count > 0}).share(replay: 1)
//
        //合并
        let everythingValid = Observable.combineLatest(
            companyIdValid,
            agentIdValid,
            tradeModeValid,
            poReferenceValid
          ) { $0 && $1 && $2 && $3} // 取用户名和密码同时有效
          .share(replay: 1)

        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    
    func setData(){
        self.viewModel =  CreateJobModelHelper.shared.createJobViewModel
        self.changeTradeMode(self.viewModel.summaryViewModel.trade_mode)
        self.poReferenceTextField.textField.text = self.viewModel.summaryViewModel.customer_po
        //
        self.checkEverythingValid()
    }
    func getAgentList(){
        guard self.viewModel.summaryViewModel.company_id != 0 else { return }
        let service = CreateJobService()
        service.setBlockAfterNetwork { [weak self] (result, _) in
            ModelViewUtil.shared.hideLoadingView()
            guard let strongSelf = self else {return}
            if let list = result as? [AgentModel]{
                if list.count == 1 && strongSelf.viewModel.summaryViewModel.agent_id == 0{//只有一条数据，且没有初始化过默认选中
                    strongSelf.viewModel.summaryViewModel.agent_id = list[0].id
                    strongSelf.viewModel.summaryViewModel.agent_name = list[0].name
                }
                strongSelf.agentListObserver.accept(list)
            }
        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code,error)
        }
        ModelViewUtil.shared.showLoadingView()
        service.getAgentList(self.viewModel.summaryViewModel.company_id)
    }
}
